package com.njrsrc.android.tasks;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import com.njrsrc.R;
import com.njrsrc.android.app.MainActivity;
import com.njrsrc.common.utils.Device;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class BootTask extends AsyncTask<Object, Integer, Void> {

	private Context context;
	private Handler bootHandler;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 2) {
			return null;
		}
		context = (Context) params[0];
		bootHandler = (Handler) params[1];
		// 创建应用所需要的文件夹
		try {
			Helpers.createFS();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private State checkNetworkInfo() {
		ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return mobile;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return wifi;
		return null;

	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		// 检测网络状态
		State networkState = checkNetworkInfo();
		if (networkState == null) {
			// 弹出对框框让用户选择是否跳转至设置网络界面
			AlertDialog builder = new AlertDialog.Builder(context).setTitle(R.string.prompt)
					.setMessage(R.string.networkPrompt).setPositiveButton(R.string.ok, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 跳转到网络设置界面并退出应用
							context.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
							((Activity) context).finish();
						}
					}).setNegativeButton(R.string.cancel, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 退出应用
							Intent mainIntent = new Intent();
							mainIntent.setClass(context, MainActivity.class);
							context.startActivity(mainIntent);
							((Activity) context).finish();
						}
					}).show();
			return;
		}
		// 取屏幕的分辨率
		Device.screenWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
		Device.screenHeight = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight();

		Message msg = bootHandler.obtainMessage();
		msg.what = MsgID.BOOT_COMPLETE;
		bootHandler.sendMessage(msg);
	}
}
